﻿using System.Configuration;
using System.Globalization;
using System.Threading;

namespace Vibstudio.X4NET.Globalization
{
    public abstract class LabelingProviderBase
    {
        private const string DEFAULT_APP_LANG_KEY = "appLang";

        private string _lang;

        public string AppLangFileName { get; set; }

        public string AppLangKey { get; set; }

        public string AppLang
        {
            get
            {
                if (!string.IsNullOrEmpty(_lang))
                {
                    SetCultureOnThread(_lang);

                    return Thread.CurrentThread.CurrentCulture.Name;
                }
                
                return ConfigurationManager.AppSettings[AppLangKey] ?? Thread.CurrentThread.CurrentCulture.Name;
            }
            set
            {
                _lang = value;
                SetCultureOnThread(_lang);
            }
        }

        protected string DefaultAppLangKey
        {
            get { return DEFAULT_APP_LANG_KEY; }
        }

        private void SetCultureOnThread(string lang)
        {
            if (!string.IsNullOrEmpty(lang))
            {
                CultureInfo cultureInfo = new CultureInfo(lang);
                Thread.CurrentThread.CurrentCulture = cultureInfo;
                Thread.CurrentThread.CurrentUICulture = cultureInfo;
            }
        }
    }
}